# coding:utf-8
# Project:pyinterface
# author:wj
# time:2022/12/30 17:27
# Email:1305137785@qq.com
import json
import re
import allure
import requests
from requests_toolbelt import MultipartEncoder
from conf.settings import img_info,kfw_info
from tool.handle_attribute import HandleAttribute
from tool.handle_path import image_dir
from tool.handle_response import HandleResponse
from loguru import logger
from tool.handle_cookie import HandleCookie
class HandleRequests:
    def __init__(self):
        self.header = {"locale": "zh_CN"}
        self.handle_response = HandleResponse()
        self.handle_cookie = HandleCookie()

    # 这里配置不同项目的请求域名，根据项目自行配置
    @allure.step('请求url的预置处理')
    def __hanle_url(self,url,project_name):
        #拼接url地址(域名+端口+接口地址)
        if url.startswith("http") or url.startswith("https"):
            allure.attach(body='请求url不需要做处理',name='请求url不需要做处理')
            print('不做处理')
        else:
            if project_name=='kuaifuwang':
                allure.attach(body='给url配置项目域名',name='给url配置项目域名')
                url = kfw_info["host"]+url
            elif(project_name=='zhixu'):
                print('这里配置智序项目的url')
            else:
                print('这里是占位')
        #获取需要替换的key
        key_list = re.findall(r"#(\w.+?)#",url)
        if len(key_list) >0:
            for key in key_list:
                if hasattr(HandleAttribute,key):
                    url = url.replace(f"#{key}#",str(getattr(HandleAttribute,key)))
                    allure.attach(body=f'{url}', name='url需要替换')
                else:
                    print(f"{key}属性名称不存在，请检查一下全局属性设置是否错误")
            return url
        else:
            print("url地址不需要替换")
            return url
    #请求头处理：鉴权，不同的项目有不同的鉴权方式，根据项目来分析，到底怎么样鉴权，写在测试用例excel里，提取鉴权cookie也行，
    # 主要看项目是什么样的，然后代码再做出调整
    @allure.step('请求header的处理')
    def __handle_headers(self,project_name):
        if project_name == "kuaifuwang":
            if hasattr(HandleAttribute,"kuaifuwang_cookie"):
                cookie = getattr(HandleAttribute,"kuaifuwang_cookie")
                allure.attach(body=f'{cookie}', name='请求头cookie处理')
                self.header['Cookie'] = cookie
            else:
                cookie = self.handle_cookie.kfw_login_cookie()
                self.header['Cookie'] = cookie
                allure.attach(body=f'header【cookie】={cookie}', name='请求头cookie处理')
        elif project_name == "test":
            if hasattr(HandleAttribute,"token"):
                token = getattr(HandleAttribute,"token")
                self.header['token'] = token
                allure.attach(body=f'header【token】={token}', name='请求头token处理',
                              attachment_type=allure.attachment_type.TEXT)
            else:
                allure.attach(body='该接口不需要鉴权',name='该接口不需要鉴权',
                              attachment_type=allure.attachment_type.TEXT)
        else:
            allure.attach(body='该接口不需要鉴权', name='该接口不需要鉴权',
                          attachment_type=allure.attachment_type.TEXT)
            print("该接口不需要鉴权")
    #图片上传接口单独处理
    def __upload_image(self,method,url):
        with open(file=image_dir,mode="rb") as file:
            image = file.read()
            data = MultipartEncoder(fields={
                "file": (img_info["file_name"], image, img_info["file_type"])
            })
            #修改请求头为图片上传的类型 multipart/form-data
            self.header["Content-Type"] = data.content_type
            response = requests.request(method=method,url=url,data=data,headers=self.header)
        #图片上上传接口修改了Content-Type的值，我们要用完之后改回来变成json，方便后面的接口继续使用
        self.header["Content-Type"] ="application/json;charset=UTF-8"
        return response
    @allure.step('发送请求并处理响应数据')
    #发送请求
    def send_request(self,method,url,data,is_upload=None,project_name=None,contenttype=None):
        #请求地址处理，接口地址的数据是从响应结果提取出来的
        new_url = self.__hanle_url(url,project_name)
        logger.info(f'请求url：{new_url}')
        #鉴权处理
        self.__handle_headers(project_name)
        logger.info(f'请求方式是：{method}')
        logger.info(f'请求参数是：{data}')
        #图片上传接口
        if str(is_upload) == "1":
            #图片上传接口
            response = self.__upload_image(method=method,url=new_url,)
        else:
            if method=="GET":
                response = self.request_get(new_url,data,header=self.header)
            else:
                response = self.request_post(method, new_url, data, header=self.header,content_type=contenttype)
                print('另外类型的的请求接口')
        #响应结果处理
        response = self.handle_response.handle_response(response=response)
        print("处理后的响应结果：")
        print(response)
        return response
    # 封装GET请求
    @allure.step('发送请求')
    def request_get(self,url,data=None,header=None):
        try:
            response = requests.get(url=url,params=data,headers=header)
            response.raise_for_status()
            print('提交url是{}'.format(response.request.url))
        except Exception as error:
            print('----异常信息是---', error)
            logger.error(error)
            allure.attach(body=f'{error}', name='异常信息是',
                          attachment_type=allure.attachment_type.TEXT)
        else:
            return response
    # 封装post请求
    @allure.step('发送请求')
    def request_post(self,method,url,data,header,content_type):
        try:
            if content_type == "JSON":
                response = requests.request(method=method,url=url,json=data,headers=header)
            # response = requests.post(url=url, data=data,headers=header)
            else:
                response = requests.request(method=method, url=url, data=data, headers=header)
            response.raise_for_status()
            print('提交参数是{}{}'.format(response.request.url, response.request.body))
        except Exception as error:
            print('----异常信息是---', error)
            logger.error(error)
            allure.attach(body=f'{error}', name='异常信息是',
                          attachment_type=allure.attachment_type.TEXT)
        else:
            return response